from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from uvicorn import run
from logic_rule.tjs_rule import tjs_rule_check
from logic_rule.rj_rule import rj_rule_check
from logic_rule.llt_rule import llt_rule_check
from logic_rule.why_rule import why_rule_check
from enetity_extraction.Information_Extraction import extract_information
# 重点信息抽取
from enetity_extraction.key_entity_extractor import key_entity_extractor, money_entity_extractor


app = FastAPI()
# 跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
# 定义请求体模型
class Object(BaseModel):
    Judgment_document: str

# 信息核对接口
@app.post("/api/key_info_extractor")
def key_info_extractor(object: Object):
    response = {"code": 0,
                "data": {"money": [], "entity": []},
                "msg": "successful"}
    
    input_text = object.Judgment_document
    # print("from:" , input_text)
    input_text_list = input_text.split('\n')
    print("input_text_list: ", input_text_list)
    input_text = "".join(input_text_list)
    money_infos = money_entity_extractor(input_text_list)
    if money_infos:
        response["data"]["money"] = money_infos
        # for item in money_infos:
        #     print(item)
        #     print("*" * 20)
    
    key_entitys = key_entity_extractor(input_text)
    if key_entitys:
        response["data"]["entity"] = key_entitys
        # for item in key_entitys:
        #     print(item)
        #     print("*"* 20)
    return response
    
    
    
@app.post("/proof/")
def calculate_similarity(object: Object):

    input_text = object.Judgment_document
    input_text_list = input_text.split('\n')
    result_list = []

    try:
        extraction_result = extract_information(input_text_list)
    except Exception as e:
        return{
            "code": -1,
            "data": [],
            "message": f"extract_information 出错: {str(e)}"
        }
    print(input_text_list)
    try:
        result_list.extend(tjs_rule_check(extraction_result))
    except Exception as e:
        print(f"tjs_rule_check 出错: {str(e)}")

    try:
        result_list.extend(rj_rule_check(extraction_result))
    except Exception as e:
        print(f"rj_rule_check 出错: {str(e)}")

    try:
        result_list.extend(llt_rule_check(extraction_result))
    except Exception as e:
        print(f"llt_rule_check 出错: {str(e)}")

    try:
        result_list.extend(why_rule_check(input_text_list, extraction_result))
    except Exception as e:
        print(f"why_rule_check 出错: {str(e)}")

    ## 填充结果中的word字段
    for item in result_list:
        if item['word']:
            continue
        start = item.get("start", 0)
        end = item.get("end", 0)
        if start >= 0 and end > 0 and (end - start) > 0:
            item['word'] = input_text[start: end]
        if not item.get("correct"):
            item["opt"] = '无'
            
    return {
        "code": 0,
        "data": result_list,
        "message": "ok"
    }

if __name__ == "__main__":
    run(app="API:app", host="0.0.0.0", port=7545, workers=1)#公司那边
    # run(app="API:app", host="0.0.0.0", port=8888, workers=1)#学校这边


